<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeKey"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="empData"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="changeEmp"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column
            label="头像"
            align="center"
            prop="staffPhoto"
          >
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username"> {{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            prop="username"
          />
          <el-table-column
            label="手机号"
            sortable
            prop="mobile"
          />
          <el-table-column
            label="工号"
            sortable
            prop="workNumbe"
          />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
          >
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment===1">正式</span>
              <span v-else-if="row.formOfEmployment===2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column
            label="部门"
            prop="departmentName"
          />
          <el-table-column
            label="入职时间"
            sortable
            prop="timeOfEntry"
          />
          <el-table-column
            label="操作"
          >
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="bunRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定要删除吗？"
                @onConfirm="btnremove(row.id)"
              >
                <el-button slot="reference" v-permission="'del-employee'" size="mini" type="text" class="btn">删除</el-button>
              </el-popconfirm>
            </template></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" align="center" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog
      title="分配角色"
      :visible.sync="dialogVisible"
    >
      <el-checkbox-group
        v-model="checkedCities"
      >
        <el-checkbox v-for="item in listRole" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="mini" type="primary" @click="btnRoleOk">确定</el-button>
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
// import { getPermission } from '@/api/permission'
import { getDashboard } from '@/api/department'
import { transListToTreeData } from '@/utils/index'
import { getEmployeeList, exportEmployee, removeEmployee, getRoleList, getEmployee, distributionRole } from '@/api/employee'
import Filesaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: { importExcel },
  data() {
    return {
      empData: [], // 放树型的数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryParams: {
        departmentId: null, // 用来获取树型图选择了哪个id，后续调接口用
        page: 1, // 第几页
        pagesize: 10, // 每页几条
        keyword: '' // 模糊搜索
      },
      list: [], // 装初始化渲染页面用的
      total: 0, // 每条总数
      showExcelDialog: false, // 控制子组件的显示和隐藏
      dialogVisible: false, // 控制弹出层开关
      listRole: [], // 装已启用的角色列表
      checkedCities: [], // 用来绑定多选框放回的数据
      currentUserId: null // 用来控制后续调角色接口,就是当前的id

    }
  },
  created() {
    this.getDashboard()
  },
  methods: {
    async getDashboard() {
      this.empData = transListToTreeData(await getDashboard(), 0)
      this.queryParams.departmentId = this.empData[0].id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId) // 这个方法是组件自带的
      })
      this.getEmployeeList()
    },
    changeEmp(node) { // 组件自带出发事件，默认有回参
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const res = await getEmployeeList(this.queryParams)
      // console.log(res)
      this.list = res.rows
      this.total = res.total
    },
    changePage(n) { // 分页组件的事件
      this.queryParams.page = n
      this.getEmployeeList()
    },
    changeKey() { // input 事件
    // 给他整个防抖,一点击就关点这个定时器
      clearTimeout(this.trim)
      this.trim = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    async exportEmployee() { // xlsx 表格导出
      const res = await exportEmployee()
      console.log(res)
      Filesaver.saveAs(res, '员工信息表.xlsx') // 这是一个包，这是包里面的一个方法
    },
    async btnremove(id) {
      await removeEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.$message.success('删除员工成功')
      this.getEmployeeList()
    },
    async bunRole(id) { // 点击角色按钮
      this.currentUserId = id
      this.listRole = await getRoleList()
      const { roleIds } = await getEmployee(id)
      this.checkedCities = roleIds
      this.dialogVisible = true
    },
    async btnRoleOk() { // 点击确定按钮 调接口 把数据传进去
      await distributionRole({
        id: this.currentUserId,
        roleIds: this.checkedCities
      })
      this.$message.success('分配成功')
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
    .btn{
      margin-left: 10px;
    }
  }
}

</style>
